package cn.com.aisat.android.videoshow;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cn.com.aisat.android.videoshow.adapter.TvNumberAdapter;
import cn.com.aisat.android.videoshow.adapter.TvPaperAdapter;
import cn.com.aisat.android.videoshow.data.TVMovieItem;
import cn.com.aisat.android.videoshow.db.PullParseService;
import cn.com.aisat.android.videoshow.db.Utils;

public class TvDramaActivity extends Activity{
	TextView menu_path_textview;////脚尾的菜单地址
	TextView page_num;////页码
	GridView mian_gridview;//海报的容器
	LinearLayout info_linear;
	GridView tv_number_gridview;//海报对应的剧集
	TextView tv_show_tv_name;
	TextView tv_show_tv_director;//海报的相关信息
	TextView tv_show_tv_starring;// 连续剧的演员
	TextView tv_show_tv_language;//连续剧的语言
	
	//TextView tv_show_tv_content_desc;//剧情的显示
	TextView page;/////页号的显示
	/////全部电视剧的加载的容器
	List<TVMovieItem> mList;
	TvPaperAdapter tvPaperAdapter;
	TvNumberAdapter tvNumAdpater;
	List<TVMovieItem> mListitem;
	
	///用于左右的内容的转换
	boolean isLeftOver=true;
	boolean isRightOver=false;

	int mRightPos=0;
	int mLeftPos=0;
 
	int isnum=0;///暂时没有问题
	int pageCount=0;//总页数
	
	//int selectPos=0;//选择的POS
	
	//int selectNumPos=1;//选择的剧集的
	String pageText;////加载页号的文本
	String ctv_show_tv_director;
	
	String ctv_show_tv_starring;
	
	String ctv_show_tv_language;
	
	String ctv_show_tv_content_desc;
	private  String  lanpath="高清电视剧/港台电视剧";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		setContentView(R.layout.tv_drama);
		initUI();////初始化UI的信息
		initTvPaper();////初始化海报的信息
		mListitem=copy6ToListItem(mList, 0);
		
		tvPaperAdapter=new TvPaperAdapter(this, mListitem);
		//tvPaperAdapter=new TvPaperAdapter(this, mList);
		mian_gridview.setAdapter(tvPaperAdapter);
		mian_gridview.setSelection(0);
		firstOpenToInit();////第一次进去的初始化
		
		
		mian_gridview.setOnItemSelectedListener(mian_gridviewItemSelectListener);
		mian_gridview.setOnItemClickListener(mian_gridviewOnItemClickListener);
		tv_number_gridview.setOnItemClickListener(tv_number_gridviewOnItemClickListener);
		tv_number_gridview.setOnItemSelectedListener(tv_number_gridviewOnItemSelectedListener);
		 
 
	}
	public List<TVMovieItem> getdata(){
		 InputStream input = null;
		try {
			input = getResources().getAssets().open("book.xml");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Log.i("whc", "input is null "+ (input==null));
       PullParseService pull = new PullParseService();  
       List<TVMovieItem> books=null;
		try {
			books = pull.getBooks(input);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.i("whc","printStackTrace");
		}  
       for(TVMovieItem book : books){  
           Log.i("whc",book.toString());  
       } 
       return books;
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 ////向左的海报的转换
		if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT){
			if(mian_gridview.isFocused() &&  mian_gridview.getAdapter().getItemId(0)==0 && isLeftOver){
				Log.i("whc", "mian_gridview.isFocused() and position is 0");
				if(mLeftPos==mList.size()){/////没有什么意义……在第一次的时候有用而已，
					mRightPos=mList.size()-((mList.size()%6==0)?6:(mList.size()%6));//mLeftPos-6;
					mLeftPos=mRightPos;
				}else{
					if(mRightPos==0){
						mRightPos=mList.size()-((mList.size()%6==0)?6:(mList.size()%6));
					}else{
						if(mRightPos-6<0){
							//mRightPos=mList.size()-6+mRightPos;
							mRightPos=0;
						}else{
							mRightPos=mRightPos-6;
						}
					}
					
				}
				
				Log.i("whc", "mian_gridview.isFocused() and mLeftPos is = "+mRightPos);
				mListitem=copy6ToListItem(mList, mRightPos);
				tvPaperAdapter=new TvPaperAdapter(this, mListitem);
				mian_gridview.setAdapter(tvPaperAdapter);
				mian_gridview.setSelection(5);
				firstOpenToInit();
				
			}
			Log.i("whc", "key onKeydown ="+tv_number_gridview.getSelectedItemId() );
			if((tv_number_gridview.getSelectedItemId()==0 || tv_number_gridview.getSelectedItemId()%10==0) && tv_number_gridview.isFocused()){
				
				info_linear.requestFocus();
				Log.i("whc", "key onKeyUp "+tv_number_gridview.getSelectedItemId() );
			}
		/*	if(tv_number_gridview.isFocused()){
				Log.i("whc", "tv_number gridview is focused ");
			}*/
			
		}
		 ////向右的海报的转换
		if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){
			if(mian_gridview.isFocused() &&  mian_gridview.getAdapter().getItemId(5)==5 && isRightOver){
				Log.i("whc", "mian_gridview.isFocused() and position is 5");
				if(mRightPos+6>mList.size()-1){
					//mRightPos=mRightPos+6-mList.size();
					mRightPos=0;
				}else{
					mRightPos=mRightPos+6;
				}
				
				mListitem=copy6ToListItem(mList, mRightPos);
				Log.i("whc", "mRightPos="+mRightPos);
				tvPaperAdapter=new TvPaperAdapter(this, mListitem);
				mian_gridview.setAdapter(tvPaperAdapter);
				mian_gridview.setSelection(0);
				firstOpenToInit();
				
			}

			if(info_linear.isFocused()){
				Log.i("whc", "info_linear is isFocused ");
				tv_number_gridview.requestFocus();
				//tv_number_gridview.getChildAt(0).requestFocus();
				tv_number_gridview.setSelection(0);
			}
		}
		/**
		 * 按OK键或向下键，焦点锁定第一集选项位置
		 */
		if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){
			if(mian_gridview.isFocused()){
				tv_number_gridview.requestFocus();
				tv_number_gridview.setSelection(0);
			}
		}
		if(keyCode==KeyEvent.KEYCODE_DPAD_UP){
			if(info_linear.isFocused()){
				return true;
			}
		}
		//按首页键，可直接返回至第一级菜单；
		if(keyCode==KeyEvent.KEYCODE_HOME){
			////按HOME的时候 。
			
		}
		//按返回键，返回到上一级层；
		if(keyCode==KeyEvent.KEYCODE_BACK){
			//按返回键，返回到上一级层；
			
		}
		Log.i("whc", "key down" );
		return super.onKeyDown(keyCode, event); 
	}
/*	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		Log.i("whc", "key onKeyUp "+isnum );
		if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT){
			if(isnum==1){
				isnum=isnum+1;
			}else if(isnum==2){
				info_linear.requestFocus();
				isnum=0;
			}else{
				
			}
		}
		
		return super.onKeyUp(keyCode, event);
	}*/
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		Log.i("whc", "key onKeyUp ="+tv_number_gridview.getSelectedItemId() );
		if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT){

		}
		
		return super.onKeyUp(keyCode, event);
	}
	/***
	 * 加载下面的剧集和剧情的用关信息.
	 */
	private void firstOpenToInit() {
		tvNumAdpater=new TvNumberAdapter(TvDramaActivity.this,(TVMovieItem)tvPaperAdapter.getItem(0));
		tv_number_gridview.setAdapter(tvNumAdpater);
		tv_show_tv_name.setText(((TVMovieItem)tvPaperAdapter.getItem(0)).getName());
		tv_show_tv_director.setText(((TVMovieItem)tvPaperAdapter.getItem(0)).getTv_show_tv_director());
		tv_show_tv_starring.setText(((TVMovieItem)tvPaperAdapter.getItem(0)).getTv_show_tv_starring());
		tv_show_tv_language.setText(((TVMovieItem)tvPaperAdapter.getItem(0)).getTv_show_tv_language() + " " +
				((TVMovieItem)tvPaperAdapter.getItem(0)).getTv_show_tv_origin());
		//tv_show_tv_content_desc.setText(ctv_show_tv_content_desc+((TVMovieItem)tvPaperAdapter.getItem(0)).getTv_show_tv_content_desc());	
		int cruPage=mRightPos/6+1;
		page_num.setText(pageText+" "+cruPage+" / " +pageCount);
		 
	}

	/**
	 * 复制list的数据到item中去，用于显示用的，list为主要的源数据源，
	 * pos就第一页的最后一个或是最前一个
	 * 这是不去判断是最后一个还是最前面一个。以后再说
	 * @param list
	 * @param pos
	 */
	public List<TVMovieItem> copy6ToListItem(List<TVMovieItem> list,int pos){ 
		List<TVMovieItem> item2=new ArrayList<TVMovieItem>();
		for(int i=0;i<6;i++){
			if(pos==mList.size()){
				pos=-1;
			}
			if(pos==-1) break;
			TVMovieItem item=list.get(pos);
			pos=pos+1;
			
			item2.add(item);
			
		}
		return item2;
	}

	/**
	 * 初始化UI
	 */
	private void initUI() {
		menu_path_textview=(TextView)findViewById(R.id.menu_path_textview);
		page_num=(TextView)findViewById(R.id.page_num);
		mian_gridview=(GridView)findViewById(R.id.mian_gridview);
		tv_number_gridview=(GridView)findViewById(R.id.tv_number_gridview);
		
		tv_show_tv_name=(TextView)findViewById(R.id.tv_show_tv_name);
		tv_show_tv_director=(TextView)findViewById(R.id.tv_show_tv_director);
		tv_show_tv_starring=(TextView)findViewById(R.id.tv_show_tv_starring);
		tv_show_tv_language=(TextView)findViewById(R.id.tv_show_tv_language);
		//tv_show_tv_content_desc=(TextView)findViewById(R.id.tv_show_tv_content_desc);
		info_linear=(LinearLayout)findViewById(R.id.info_linear);
		pageText=getResources().getString(R.string.pagenumber);
		menu_path_textview.setText(lanpath);
		 ctv_show_tv_director=getResources().getString(R.string.tv_show_tv_director);
		
		 ctv_show_tv_starring=getResources().getString(R.string.tv_show_tv_starring);
		
		 ctv_show_tv_language=getResources().getString(R.string.tv_show_tv_language);
		
		// ctv_show_tv_content_desc=getResources().getString(R.string.tv_show_tv_content_desc);
	}
	/**
	 * 初始化海报的信息，取得全部的的海报的信息
	 */
	private void initTvPaper() {
		/////取得连续剧的全部信息。从哪里来的数据？
		mList=new ArrayList<TVMovieItem>();
		//mList=getAllTvInfo();
		 InputStream input = null;
		try {
			input = getResources().getAssets().open("book.xml");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Log.i("whc", "input is null "+ (input==null));
      PullParseService pull = new PullParseService();  
      List<TVMovieItem> books=null;
		try {
			books = pull.getBooks(input);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.i("whc","printStackTrace");
		}  
      for(TVMovieItem book : books){  
          Log.i("whc",book.toString());  
      } 
		mList= books;
		mLeftPos=mList.size();
		pageCount=mList.size()/6;
		if(mList.size()%6!=0){
			pageCount=pageCount+1;
		}
	}



	private List<TVMovieItem> getAllTvInfo() {
		 //////以下是假数据，实现是怎样取的，我也不知道 。
		mList=Utils.getTVItems();
		return mList;
	}
	
	////用于左右的转换.
	OnItemSelectedListener mian_gridviewItemSelectListener=new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) { 
			tvNumAdpater=new TvNumberAdapter(TvDramaActivity.this,(TVMovieItem)tvPaperAdapter.getItem(position));
			tv_number_gridview.setAdapter(tvNumAdpater);
			tv_show_tv_name.setText(((TVMovieItem)tvPaperAdapter.getItem(position)).getName());
			tv_show_tv_director.setText(((TVMovieItem)tvPaperAdapter.getItem(position)).getTv_show_tv_director());
			tv_show_tv_starring.setText(((TVMovieItem)tvPaperAdapter.getItem(position)).getTv_show_tv_starring());
			tv_show_tv_language.setText(((TVMovieItem)tvPaperAdapter.getItem(position)).getTv_show_tv_language() + " " +
					((TVMovieItem)tvPaperAdapter.getItem(position)).getTv_show_tv_origin());
			//tv_show_tv_content_desc.setText(ctv_show_tv_content_desc+((TVMovieItem)tvPaperAdapter.getItem(position)).getTv_show_tv_content_desc());	
			
			if(position==0){
				isLeftOver=true;
			}else{
				isLeftOver=false;
			}
			/*if(position==5){
				isRightOver=true;	
			}else{
				isRightOver=false;
			}*/
			if(position==mListitem.size()-1){
				isRightOver=true;	
			}else{
				isRightOver=false;
			}
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
			
		}
	};
	/**
	 * 再按OK，开始播放第一集
	 */
	OnItemClickListener mian_gridviewOnItemClickListener=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			tv_number_gridview.requestFocus();
			tv_number_gridview.setSelection(0);
			
		}
	};
		/////暂时没有用.
		OnItemSelectedListener tv_number_gridviewOnItemSelectedListener= 
			new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
/*				if(id==1 || id==9){
					if(isnum==0){
						isnum=isnum+1;
					}else{
						isnum=0;
					}
				}*/
				Log.i("whc", "if(onFocusChange==1){positon="+position+" id="+id+" isnum="+isnum);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		};
		
		/////用于点击播放用的
		OnItemClickListener tv_number_gridviewOnItemClickListener=
				new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//连续剧的路径是用filePath和剧集组成的
				String data=((TVMovieItem)tv_number_gridview.getAdapter().getItem(0)).getFilepath();
				
				data=data+"-"+position;
				
				Log.i("whc", data);
				
				/////以下是播放的方式 ,怎样去调了..
				////自己发挥.
				
			}
		};
		public static Bitmap getImage(String Url) throws Exception {
		try {
			URL url = new URL(Url);
			String responseCode = url.openConnection().getHeaderField(0);
		if (responseCode.indexOf("200") < 0)
			throw new Exception("图片文件不存在或路径错误，错误代码：" + responseCode);
		return BitmapFactory.decodeStream(url.openStream());
			} catch (IOException e) {
				throw new Exception(e.getMessage());
			}
		}	
}
